package com.cci.kangdao.fieldService.service.impl;

import com.cci.kangdao.dao.WorkOrderDrDao;
import com.cci.kangdao.dto.BaseResponse;
import com.cci.kangdao.fieldService.dao.FieldServiceInvestigationDao;
import com.cci.kangdao.fieldService.dao.FieldServiceInvestigationReportDao;
import com.cci.kangdao.fieldService.dao.FieldServiceReportResultDao;
import com.cci.kangdao.fieldService.dao.FieldServiceTemplateDao;
import com.cci.kangdao.fieldService.dao.FieldServiceTemplateParamDao;
import com.cci.kangdao.fieldService.model.FieldServiceInvestigation;
import com.cci.kangdao.fieldService.model.FieldServiceInvestigationReport;
import com.cci.kangdao.fieldService.model.FieldServiceReportResult;
import com.cci.kangdao.fieldService.model.FieldServiceTemplate;
import com.cci.kangdao.fieldService.model.FieldServiceTemplateParam;
import com.cci.kangdao.fieldService.model.FieldServiceWorkOrder;
import com.cci.kangdao.fieldService.model.ReportResult;
import com.cci.kangdao.fieldService.model.WorkOrderReport;
import com.cci.kangdao.fieldService.model.type.FieldServiceTemplateParamType;
import com.cci.kangdao.fieldService.model.type.FieldServiceTemplateType;
import com.cci.kangdao.fieldService.model.type.SyncInterface;
import com.cci.kangdao.fieldService.service.FieldServiceReportService;
import com.cci.kangdao.fieldService.service.SyncProcessor;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author William Du
 * @date 2020/2/26
 */
@Service
public class FieldServiceReportServiceImpl implements FieldServiceReportService {

    private static final Logger logger = Logger.getLogger(FieldServiceReportService.class);

    @Resource
    private FieldServiceInvestigationDao fieldServiceInvestigationDao;

    @Resource
    private FieldServiceTemplateDao fieldServiceTemplateDao;

    @Resource
    private FieldServiceTemplateParamDao fieldServiceTemplateParamDao;

    @Resource
    private FieldServiceReportResultDao fieldServiceReportResultDao;

    @Resource
    private SyncProcessor syncProcessor;

    @Resource
    private FieldServiceInvestigationReportDao fieldServiceInvestigationReportDao;

    @Resource
    private WorkOrderDrDao workOrderDrDao;

    @Override
    public void syncReport(FieldServiceWorkOrder workOrder) {
        WorkOrderReport workOrderReport = new WorkOrderReport();
        workOrderReport.setOrderId(workOrder.getId());
        List<WorkOrderReport.Investigation> investigationList = new ArrayList<>();
        // 赋值调查列表
        List<FieldServiceInvestigation> dataInvestigationList = fieldServiceInvestigationDao.selectListByOrderId(workOrder.getId());
        List<Long> activeTemplateIdList = fieldServiceTemplateDao.selectActiveTemplateIdList(workOrder.getChannel());
        if (CollectionUtils.isEmpty(activeTemplateIdList)) {
            return;
        }
        if (CollectionUtils.isNotEmpty(dataInvestigationList)) {
            for (FieldServiceInvestigation dataInvestigation : dataInvestigationList) {
                WorkOrderReport.Investigation investigation = new WorkOrderReport.Investigation();
                investigation.setTitle(dataInvestigation.getTitle());
                investigation.setInvestigationNo(dataInvestigation.getInvestigationNo());

                // 赋值报告列表
                List<WorkOrderReport.InvestigationReport> investigationReportList = new ArrayList<>();
                List<FieldServiceInvestigationReport> reportList = fieldServiceInvestigationReportDao.selectReportList(dataInvestigation.getId());
                if (CollectionUtils.isNotEmpty(reportList)) {
                    for (FieldServiceInvestigationReport report : reportList) {
                        if (!activeTemplateIdList.contains(report.getTemplateId())) {
                            // 模板已经失效，此时不传输该模板数据值
                            continue;
                        }

                        FieldServiceTemplate template = fieldServiceTemplateDao.selectByPrimaryKey(report.getTemplateId());
                        // 拼装报告信息
                        WorkOrderReport.InvestigationReport investigationReport = new WorkOrderReport.InvestigationReport();
                        investigationReport.setReportTitle(report.getReportTitle());
                        investigationReport.setTemplateType(template.getType());
                        investigationReport.setTemplateNo(template.getCrmNo());
                        // 拼装Value值数据
                        List<WorkOrderReport.ReportData> dataList = new ArrayList<>();
                        if (FieldServiceTemplateType.CDS.getCode().equals(report.getTemplateType())) {
                            // 如果是CDS报告
                            dataList.addAll(generateCDSReportList(report));
                        } else {
                            // 非CDS报告
                            // 获取所有模板片段填充的结果
                            List<FieldServiceReportResult> reportResultList = fieldServiceReportResultDao.selectByReportId(report.getId());
                            if (CollectionUtils.isNotEmpty(reportResultList)) {
                                // 遍历所有结果
                                for (FieldServiceReportResult result : reportResultList) {
                                    if (StringUtils.isNotEmpty(result.getData())) {
                                        List<WorkOrderReport.ReportData> reportDataList = new ArrayList<>();
                                        // 将数据库中json转换为结果对象列表
                                        List<WorkOrderReport.DataReportData> dataReportDataList = JsonUtils.convertJsonArrayToList(result.getData(), WorkOrderReport.DataReportData.class);
                                        if (CollectionUtils.isNotEmpty(dataReportDataList)) {
                                            // 遍历结果对象
                                            for (WorkOrderReport.DataReportData dataReportData : dataReportDataList) {
                                                // 生成给CRM的结果对象
                                                WorkOrderReport.ReportData reportData = new WorkOrderReport.ReportData();
                                                reportData.setKey(dataReportData.getKey());
                                                reportData.setValue(dataReportData.getValue());
                                                // 如果附件列表不为空，开始拼装附件对象列表
                                                if (CollectionUtils.isNotEmpty(dataReportData.getExtraData())) {
                                                    List<WorkOrderReport.ExtraData> extraDataList = new ArrayList<>();
                                                    // 获取到当前参数的附件类型
                                                    FieldServiceTemplateParam param = fieldServiceTemplateParamDao.selectBySectionAndKey(result.getSectionId(), dataReportData.getKey());
                                                    if (null == param) {
                                                        continue;
                                                    }
                                                    for (String extraDataUrl : dataReportData.getExtraData()) {
                                                        WorkOrderReport.ExtraData extraData = new WorkOrderReport.ExtraData();
                                                        // 将参数的附件类型赋值到附件对象的type字段上
                                                        extraData.setExtraType(param.getExtraType());
                                                        // 将附件链接赋值到附件对象的url字段上
                                                        extraData.setExtraUrl(extraDataUrl);
                                                        extraDataList.add(extraData);
                                                    }
                                                    // 将处理好的附件对象列表放入报告中
                                                    reportData.setExtraData(extraDataList);
                                                }
                                                // 将结果赋值到报告片段内
                                                reportDataList.add(reportData);
                                            }
                                        }
                                        // 报告增加片段内所有结果列表
                                        dataList.addAll(reportDataList);
                                    }
                                }
                            }
                        }
                        // 如果报告内，结果列表不为空，说明填写了内容
                        if (CollectionUtils.isNotEmpty(dataList)) {
                            // 将报告信息放入调查对象
                            investigationReport.setData(dataList);
                            // 将报告信息放入报告列表
                            investigationReportList.add(investigationReport);
                        }
                    }
                }
                investigation.setTemplateList(investigationReportList);
                if (CollectionUtils.isNotEmpty(investigation.getTemplateList())) {
                    investigationList.add(investigation);
                }
            }
        }
        workOrderReport.setInvestigationList(investigationList);
        syncProcessor.syncInfoToCrm(workOrder.getItemId(), SyncInterface.SYNC_REPORT, workOrderReport);
    }

    @Override
    public List<ReportResult> getReportResultList(FieldServiceInvestigationReport report) {
        List<ReportResult> reportResultList = new ArrayList<>();
        List<FieldServiceReportResult> resultList = fieldServiceReportResultDao.selectByReportId(report.getId());
        Map<String,ReportResult> resultMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(resultList)){
            for(FieldServiceReportResult result:resultList){
                String resultData =  result.getData();
                if(StringUtils.isEmpty(resultData)){
                    continue;
                }
                List<ReportResult> dataReportResultList = JsonUtils.convertJsonArrayToList(resultData,ReportResult.class);
                if(CollectionUtils.isNotEmpty(dataReportResultList)){
                    for(ReportResult reportResult:dataReportResultList){
                        if(StringUtils.isNotEmpty(reportResult.getValue()) || CollectionUtils.isNotEmpty(reportResult.getExtraData())){
                            resultMap.put(reportResult.getKey(),reportResult);
                        }
                    }
                }
            }
        }

        List<FieldServiceTemplateParam> params = fieldServiceTemplateParamDao.selectListByTemplateId(report.getTemplateId());
        if(CollectionUtils.isEmpty(params)){
            return reportResultList;
        }else{
            for(FieldServiceTemplateParam param:params){
                ReportResult reportResult = new ReportResult();
                reportResult.setName(param.getParamName());
                // 如果是pdf报告
                if(FieldServiceTemplateParamType.CDS_PDF_URL.getCode().equals(param.getParamType())){
                    // CDS的pdf报告
                    if(report.getIsComplete().equals(1)){
                        reportResult.setValue(getPdfUrl(report.getDrWorkOrderId()));
                        reportResult.setExtraData(new ArrayList<>());
                    }else{
                        reportResult.setValue("");
                        reportResult.setExtraData(new ArrayList<>());
                    }
                }else if(FieldServiceTemplateParamType.CDS_WEB_URL.getCode().equals(param.getParamType())){
                    // CDS的WEB端报告
                    reportResult.setValue(getWebUrl(report.getDrWorkOrderId()));
                    reportResult.setExtraData(new ArrayList<>());
                }else{
                    // 普通参数
                    if(resultMap.containsKey(param.getParamKey())){
                        ReportResult dataResult = MapUtils.getObject(resultMap,param.getParamKey());
                        if(StringUtils.isNotEmpty(dataResult.getValue())){
                            reportResult.setValue(dataResult.getValue());
                        }else {
                            reportResult.setValue("");
                        }
                        if(CollectionUtils.isNotEmpty(dataResult.getExtraData())){
                            reportResult.setExtraData(dataResult.getExtraData());
                        }else{
                            reportResult.setExtraData(new ArrayList<>());
                        }
                    }else{
                        reportResult.setValue("");
                        reportResult.setExtraData(new ArrayList<>());
                    }
                }
                reportResultList.add(reportResult);
            }
        }

        // 这里是只显示填充项的逻辑
        /*Map<String,String> paramKeyNameMap = new HashMap<>(params.size());
        for(FieldServiceTemplateParam param:params){
            paramKeyNameMap.put(param.getParamKey(),param.getParamName());
        }

        if(CollectionUtils.isNotEmpty(resultList)){
            for(FieldServiceReportResult result:resultList){
                String resultData =  result.getData();
                if(StringUtils.isEmpty(resultData)){
                    continue;
                }
                List<ReportResult> dataReportResultList = JsonUtils.convertJsonArrayToList(resultData,ReportResult.class);
                if(CollectionUtils.isNotEmpty(dataReportResultList)){
                    for(ReportResult reportResult:dataReportResultList){
                        String paramName = MapUtils.getString(paramKeyNameMap,reportResult.getKey());
                        if(StringUtils.isNotEmpty(paramName) && StringUtils.isNotEmpty(reportResult.getValue())){
                            reportResult.setName(paramName);
                            reportResultList.add(reportResult);
                        }
                    }
                }
            }
        }*/
        return reportResultList;
    }

    private List<WorkOrderReport.ReportData> generateCDSReportList(FieldServiceInvestigationReport fieldServiceInvestigationReport) {
        List<WorkOrderReport.ReportData> reportDataList = new ArrayList<>();
        // 拼装CDS报告参数类型的数据，值为7,8
        String[] types = new String[]{FieldServiceTemplateParamType.CDS_PDF_URL.getCode(), FieldServiceTemplateParamType.CDS_WEB_URL.getCode()};
        for (String type : types) {
            // 通过模板类型+参数类型值获取参数对象
            FieldServiceTemplateParam cdsParam = fieldServiceTemplateParamDao.selectCDSParamKey(fieldServiceInvestigationReport.getTemplateId(), type);
            if (null != cdsParam) {
                // 通过报告上关联的诊断工单ID获取到诊断工单编号
                String reportUrl = null;
                // 通过参数类型，分别拼装web报告和pdf报告
                if (FieldServiceTemplateParamType.CDS_WEB_URL.getCode().equals(cdsParam.getParamType())) {
                    reportUrl = getWebUrl(fieldServiceInvestigationReport.getDrWorkOrderId());
                } else {
                    reportUrl = getPdfUrl(fieldServiceInvestigationReport.getDrWorkOrderId());
                }
                WorkOrderReport.ReportData reportData = new WorkOrderReport.ReportData();
                // 将CDS参数中的paramKey和报告url拼装在一起，并加入报告结果列表
                reportData.setKey(cdsParam.getParamKey());
                reportData.setValue(reportUrl);
                reportDataList.add(reportData);
            }
        }
        return reportDataList;
    }

    private String getWebUrl(Long drWorkOrderId){
        //获取工单密钥
        String reportUrl = "";
        String secretKey = workOrderDrDao.getSecretKeyById(drWorkOrderId);
        if (StringUtils.isEmpty(secretKey)) {
            secretKey = workOrderDrDao.getOrderNoById(drWorkOrderId);
        }
        if(StringUtils.isNotEmpty(secretKey)){
            String webUrl = PropertiesUtil.getProperties("projectconfig.properties", "drDiagnoseReport").trim();
            reportUrl = webUrl + secretKey;
        }
        return reportUrl;
    }

    private String getPdfUrl(Long drWorkOrderId) {
        String generatePdfUrl = PropertiesUtil.getProperties("projectconfig.properties", "drPdfDiagnoseReport").trim();
        generatePdfUrl = generatePdfUrl + drWorkOrderId;
        logger.info("调用System项目生成PDF诊断报告");
        String response = HttpUtils.get(generatePdfUrl, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return EntityUtils.toString(httpEntity);
                }else{
                    logger.error("调用System项目生成PDF诊断报告发送异常"+response.getStatusLine()+response);
                }
                return null;
            }
        });
        logger.info("调用System项目生成PDF诊断报告响应："+response);
        if (StringUtils.isNotEmpty(response)) {
            BaseResponse baseResponse = JsonUtils.toJavaObject(response, BaseResponse.class);
            if (null != baseResponse && baseResponse.getStatus().equals(0)) {
                Map<String, Object> map = (Map<String, Object>) baseResponse.getData();
                return MapUtils.getString(map, "url");
            }
        }
        return null;
    }

}
